package com.mvvm.start.base.utils

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson

/**
 * @author
 * @功能: SP存储工具类
 * @Creat 12/18/20 10:18 AM
 * @Compony 465008238@qq.com
 */
class SPUtils(context: Context) {
    private val sharedPreferences: SharedPreferences =
        context.getSharedPreferences("start", Context.MODE_PRIVATE)

    /*
     * 保存手机里面的名字
     */
    private val editor: SharedPreferences.Editor

    init {
        editor = sharedPreferences.edit()
    }

    companion object {
        private lateinit var spUtils: SPUtils
        fun getInstance(context: Context): SPUtils {
            if (!::spUtils.isInitialized) {
                spUtils = SPUtils(context)
            }
            return spUtils
        }
    }

    /**
     * 存储
     */
    fun put(key: String?, `object`: Any?) {
        if (`object` is String) {
            editor.putString(key, `object` as String?)
        } else if (`object` is Int) {
            editor.putInt(key, (`object` as Int?)!!)
        } else if (`object` is Boolean) {
            editor.putBoolean(key, (`object` as Boolean?)!!)
        } else if (`object` is Float) {
            editor.putFloat(key, (`object` as Float?)!!)
        } else if (`object` is Long) {
            editor.putLong(key, (`object` as Long?)!!)
        } else {
            editor.putString(key, Gson().toJson(`object`))
        }
        editor.commit()
    }

    /**
     * 获取保存的数据
     */
    fun getSharedPreference(key: String?, defaultObject: Any?): Any? {
        return if (defaultObject is String) {
            sharedPreferences.getString(key, defaultObject as String?)
        } else if (defaultObject is Int) {
            sharedPreferences.getInt(key, (defaultObject as Int?)!!)
        } else if (defaultObject is Boolean) {
            sharedPreferences.getBoolean(key, (defaultObject as Boolean?)!!)
        } else if (defaultObject is Float) {
            sharedPreferences.getFloat(key, (defaultObject as Float?)!!)
        } else if (defaultObject is Long) {
            sharedPreferences.getLong(key, (defaultObject as Long?)!!)
        } else {
            sharedPreferences.getString(key, "")
        }
    }

    /**
     * 移除某个key值已经对应的值
     */
    fun remove(key: String?) {
        editor.remove(key)
        editor.commit()
    }

    /**
     * 清除所有数据
     */
    fun clear() {
        editor.clear()
        editor.commit()
    }
    /**
     * 退出登录
     */
    fun logout() {
        editor.remove("userBean")
        editor.commit()
    }


    /**
     * 返回所有的键值对
     */
    val all: Map<String, *> get() = sharedPreferences.all


}